package com.cep.client;

import java.nio.ByteBuffer;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RatingBar;
import android.widget.TextView;

public class ButtonListener implements OnClickListener {
	private static ButtonListener instance = null;

	public static void init(TextView consoleOutputTV_, RatingBar ratingBar_) {
		instance = new ButtonListener(consoleOutputTV_, ratingBar_);
	}

	public static ButtonListener instance() {
		return instance;
	}

	private TextView consoleOutputTV = null;
	private RatingBar ratingBar = null;

	public ButtonListener(TextView consoleOutputTV_, RatingBar ratingBar_) {
		this.consoleOutputTV = consoleOutputTV_;
		this.ratingBar = ratingBar_;
	}

	@Override
	public void onClick(View a0) {
		float nbStars = ratingBar.getRating();
		String ownIP = UDPSender.instance().getLocalIpAddress();
		String name = NameWatcher.instance().getName();

		int cap = 8 + 2 + ownIP.getBytes().length + 2 + name.getBytes().length
				+ 4;

		ByteBuffer b = ByteBuffer.allocate(cap);

		// stream ID
		b.putLong(2);
		// IP address
		short s1 = (short) ownIP.getBytes().length;
		b.putShort(s1);
		b.put(ownIP.getBytes());
		// name
		short s2 = (short) name.getBytes().length;
		b.putShort(s2);
		b.put(name.getBytes());
		// The rating
		b.putFloat(nbStars);

		if (UDPSender.instance().sendUDPMessage(b.array())) {
			consoleOutputTV.setText("New rating sent for " + name + " from "
					+ ownIP + ":\n" + nbStars + " stars out of 5");
		} else
			; // error-message is already printed
	}
}
